package com.github.prontera.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.sql.Timestamp;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.github.prontera.ApiVersion;
import com.github.prontera.RequestLogging;
import com.github.prontera.Shift;
import com.github.prontera.StatusCode;
import com.github.prontera.common.auth0.jwt.Token;
import com.github.prontera.common.auth0.jwt.TokenGenerator;
import com.github.prontera.common.auth0.jwt.exceptions.JWTCreationException;
import com.github.prontera.common.filter.CurrentUserId;
import com.github.prontera.common.filter.CurrentUserMobile;
import com.github.prontera.common.filter.IgnoreAuth;
import com.github.prontera.common.filter.MagicConstants;
import com.github.prontera.common.token.PasswordHashUtil;
import com.github.prontera.domain.AppSms;
import com.github.prontera.domain.Client;
import com.github.prontera.domain.ClientAccount;
import com.github.prontera.domain.ClientInvitation;
import com.github.prontera.domain.ClientSign;
import com.github.prontera.domain.ClientVisitor;
import com.github.prontera.domain.ClientWechat;
import com.github.prontera.domain.Issue;
import com.github.prontera.domain.IssueAnswer;
import com.github.prontera.domain.enums.AppSmsTemplateEnum;
import com.github.prontera.domain.enums.ClientFollowStatusEnum;
import com.github.prontera.domain.enums.ClientTypeEnum;
import com.github.prontera.domain.enums.RegisterChannelEnum;
import com.github.prontera.domain.enums.UserLoginTypeEnum;
import com.github.prontera.domain.enums.UserStatusEnum;
import com.github.prontera.domain.enums.YesOrNoEnum;
import com.github.prontera.model.request.LocationRequest;
import com.github.prontera.model.request.ReferTokenRequest;
import com.github.prontera.model.request.RefundRequest;
import com.github.prontera.model.request.UserLoginRequest;
import com.github.prontera.model.request.UserLoginRequest2;
import com.github.prontera.model.request.UserRegisterRequest;
import com.github.prontera.model.request.VerifCodeRequest;
import com.github.prontera.model.response.LocationResponse;
import com.github.prontera.model.response.ObjectDataResponse;
import com.github.prontera.service.AppSmsService;
import com.github.prontera.service.ClientAccountService;
import com.github.prontera.service.ClientInvitationService;
import com.github.prontera.service.ClientService;
import com.github.prontera.service.ClientSignService;
import com.github.prontera.service.ClientVisitorService;
import com.github.prontera.service.ClientWechatService;
import com.github.prontera.service.IssueAnswerService;
import com.github.prontera.service.IssueService;
import com.github.prontera.service.OrderRefundService;
import com.github.prontera.util.CookieManager;
import com.github.prontera.util.DateTimeUtil;
import com.github.prontera.util.IdWorker;
import com.github.prontera.util.RandomStringGenerator;
import com.github.prontera.util.ShareCodeUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 客户端
 */
@RestController
@Api(value = "客户端接口")
@RequestMapping(value = ApiVersion.API_V1_PREFIX + "/client")
public class ClientController {

	@Autowired
	private ClientAccountService clientAccountService;
	@Autowired
	private ClientService clientService;
	@Autowired
	private AppSmsService appSmsService;
	@Autowired
	private IssueAnswerService issueAnswerService;
	@Autowired
	private IssueService issueService;
	@Autowired
	private ClientWechatService clientWechatService;
	@Autowired
	private ClientInvitationService clientInvitationService;
	@Autowired
	private OrderRefundService orderRefundService;
	@Autowired
	private ClientVisitorService clientVisitorService;
	@Autowired
	private ClientSignService clientSignService;
	

	
	/**
	 * 发送无需用户登录验证码
	 */

	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "发送无需用户登录验证码", notes = "发送无需用户登录验证码")
	@RequestMapping(value = "test", method = RequestMethod.POST)
	public ObjectDataResponse<VerifCodeRequest> test(@RequestBody VerifCodeRequest verifCodeRequest) {
		if (verifCodeRequest == null || StringUtils.isEmpty(verifCodeRequest.getMobile())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传!");
		}
		if (verifCodeRequest.getTemplate() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "template必传!");
		}
		return new ObjectDataResponse<VerifCodeRequest>(verifCodeRequest);
	}

	/**
	 * 发送无需用户登录验证码
	 */

	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "发送无需用户登录验证码", notes = "发送无需用户登录验证码")
	@RequestMapping(value = "sendCommonVerifCode", method = RequestMethod.POST)
	public ObjectDataResponse<String> sendCommonVerifCode(@RequestBody VerifCodeRequest verifCodeRequest) {
		if (verifCodeRequest == null || StringUtils.isEmpty(verifCodeRequest.getMobile())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传!");
		}
		if (verifCodeRequest.getTemplate() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "template必传!");
		}
		String code = new RandomStringGenerator(6, true).getNewString();
		Map<String, Object> arguments = new HashMap<String, Object>();
		arguments.put("val_code", code);

		appSmsService.sendToUID(arguments, verifCodeRequest.getMobile(), verifCodeRequest.getTemplate(), code,
				DateTimeUtil.addMinutes(DateTimeUtil.getSystemDate(), 5));
		return new ObjectDataResponse<String>(code);
	}

	/**
	 * 发送验证码(需用户登录)
	 */

	@ResponseBody
	@ApiOperation(value = "发送验证码(需用户登录)", notes = "发送验证码(需用户登录)")
	@RequestMapping(value = "sendVerifCode", method = RequestMethod.POST)
	public ObjectDataResponse<String> sendVerifCode(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long userId,
			@ApiParam(name = "mobile", value = "用户mobile", hidden = true) @CurrentUserMobile String mobile, @RequestBody VerifCodeRequest verifCodeRequest) {
		if (StringUtils.isEmpty(mobile)) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传!");
		}
		if (verifCodeRequest.getTemplate() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "template必传!");
		}
		String code = new RandomStringGenerator(6, true).getNewString();
		Map<String, Object> arguments = new HashMap<String, Object>();
		arguments.put("val_code", code);
		appSmsService.sendToUserID(arguments, userId, mobile, verifCodeRequest.getTemplate(), code, DateTimeUtil.addMinutes(DateTimeUtil.getSystemDate(), 5));
		return new ObjectDataResponse<String>(code);
	}

	/**
	 * 忘记密码
	 */

	@IgnoreAuth
	@ResponseBody
	@ApiOperation(value = "忘记密码", notes = "忘记密码")
	@RequestMapping(value = "forgotPassword", method = RequestMethod.POST)
	public ObjectDataResponse<Boolean> forgotPassword(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long userId,
			@RequestBody UserLoginRequest userLoginRequest) throws NoSuchAlgorithmException, InvalidKeySpecException {
		if (StringUtils.isEmpty(userLoginRequest.getMobile())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传");
		}
		// 发送验证码
		AppSms appVerifCode = new AppSms();
		appVerifCode.setPhone(userLoginRequest.getMobile());
		appVerifCode.setOrderBy("APP_SMS.create_time desc");
		appVerifCode.setTemplate(AppSmsTemplateEnum.UPDATE_PWD);
		appVerifCode.setCode(userLoginRequest.getVerifCode());
		AppSms findAppVerifCode = appSmsService.findOne(appVerifCode);
		if (findAppVerifCode == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "无效的验证码");
		}
		if (DateTimeUtil.getMillisecondsOfTwoDate(Timestamp.from(findAppVerifCode.getActiveTime().toInstant()), DateTimeUtil.getSystemDate()) < 0) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "验证码已过期");
		}
		if (StringUtils.isEmpty(userLoginRequest.getPassword())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "password必传");
		}
		Client findUser = new Client();
		findUser.setMobile(userLoginRequest.getMobile());
		Client user = clientService.findOne(findUser);
		if (user == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户已近存在");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户处于冻结中,暂时无法操作");
		}
		Client updateUser = new Client();
		updateUser.setId(user.getId());
		updateUser.setPassword(PasswordHashUtil.createHash(userLoginRequest.getPassword()));
		if (clientService.update(updateUser) <= 0) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "密码错误,请重新登录");
		}
		return new ObjectDataResponse<Boolean>(true);
	}

	/**
	 * 查找附近得人
	 */
	@RequestLogging
	@IgnoreAuth
	@ResponseBody
	@ApiOperation(value = "查找附近得人", notes = "查找附近得人")
	@RequestMapping(value = "queryGeo", method = RequestMethod.POST)
	public ObjectDataResponse<LocationResponse> queryGeo(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long clientId, @RequestBody Client locationRequest){
		if(locationRequest.getCity()==null){
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "city必传");
		}
		if (locationRequest.getCityCode() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "cityCode必传");
		}
		if (locationRequest.getPointLat() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "pointLat必传");
		}
		if (locationRequest.getPointLog() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "pointLog必传");
		}
		if (locationRequest.getLimitStart() == null) {
			locationRequest.setPageIndex(1);
		}
		if (locationRequest.getLimitEnd() == null) {
			locationRequest.setPageSize(10);
		}
		locationRequest.setId(clientId);
		List<Client> clients = clientService.findGeoClient(locationRequest);
		LocationResponse locationResponse=new LocationResponse();
		locationResponse.setClients(clients);
		if (clients.size() < locationRequest.getPageSize()) {// 不满足一页数据
			locationResponse.setLoadedMorePage(1);
		}
		return new ObjectDataResponse<LocationResponse>(locationResponse);
	}

	/**
	 * 更新用户信息
	 */

	@ResponseBody
	@RequestLogging
	@ApiOperation(value = "更新用户信息", notes = "更新用户信息")
	@RequestMapping(value = "update", method = RequestMethod.POST)
	public ObjectDataResponse<Boolean> update(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long userId,
			@RequestBody Client updateUser) {
		updateUser.setLastBackDepositTime(null);
		updateUser.setLastLoginTime(null);
		// updateUser.setWechat(null);
		updateUser.setAmount(null);
		updateUser.setBBean(null);
		updateUser.setBeanRmbRate(null);
		updateUser.setCreateTime(null);
		updateUser.setWeiboLoginCode(null);
		updateUser.setActivityCount(null);
		updateUser.setDepositAmount(null);
		updateUser.setWeixinLoginCode(null);
		updateUser.setVideoCount(null);
		updateUser.setVipAmountId(null);
		updateUser.setVipStatus(null);
		updateUser.setUid(null);
		updateUser.setMobile(null);
		updateUser.setCid(null);
		updateUser.setScore(null);
		updateUser.setShareCode(null);
		updateUser.setWechatCount(null);
		updateUser.setLastVipExpireTime(null);
		updateUser.setLastVipTime(null);
		updateUser.setId(userId);

		if (updateUser.getBirthday() != null) {
			updateUser.setAge(OffsetDateTime.now().getYear() - updateUser.getBirthday().getYear());
		}

		if (clientService.update(updateUser) <= 0) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "参数错误 请重试!");
		}
		return new ObjectDataResponse<Boolean>(true);
	}

	/**
	 * 更新用户位置信息
	 */
	@IgnoreAuth
	@ResponseBody
	@ApiOperation(value = "更新用户位置信息", notes = "更新用户位置信息")
	@RequestMapping(value = "updateLocation", method = RequestMethod.POST)
	public ObjectDataResponse<Boolean> updateLocation(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody LocationRequest locationRequest) {
		if(clientId==null){
			return new ObjectDataResponse<Boolean>(true);
		}
		if (!clientService.updateLocation(locationRequest, clientId)) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "参数错误 请重试!");
		}
		return new ObjectDataResponse<Boolean>(true);
	}

	/**
	 * 修改密码
	 */

	@ResponseBody
	@ApiOperation(value = "修改密码", notes = "修改密码")
	@RequestMapping(value = "updatePassword", method = RequestMethod.POST)
	public ObjectDataResponse<Boolean> updatePassword(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long userId,
			@RequestBody UserLoginRequest userLoginRequest) throws NoSuchAlgorithmException, InvalidKeySpecException {
		if (StringUtils.isEmpty(userLoginRequest.getMobile())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传");
		}
		if (StringUtils.isEmpty(userLoginRequest.getPassword())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "password必传");
		}
		if (StringUtils.isEmpty(userLoginRequest.getOldPassword())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "oldPassword必传");
		}
		Client findUser = new Client();
		findUser.setMobile(userLoginRequest.getMobile());
		Client user = clientService.findOne(findUser);
		if (user == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户不存在");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户处于冻结中,暂时无法操作");
		}
		if (!PasswordHashUtil.validatePassword(userLoginRequest.getOldPassword(), user.getPassword())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "密码错误");
		}
		// 更新密码
		Client updateUser = new Client();
		updateUser.setId(user.getId());
		updateUser.setPassword(PasswordHashUtil.createHash(userLoginRequest.getPassword()));
		if (clientService.update(updateUser) <= 0) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "密码错误,请重新登录");
		}
		return new ObjectDataResponse<Boolean>(true);
	}

	/**
	 * 处理用户注册
	 */

	@IgnoreAuth
	@ResponseBody
	@ApiOperation(value = "处理用户注册", notes = "处理用户注册")
	@RequestMapping(value = "register", method = RequestMethod.POST)
	public ObjectDataResponse<Token> register(@RequestBody UserLoginRequest userLoginRequest)
			throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginRequest.getMobile())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传!");
		}
		if (StringUtils.isEmpty(userLoginRequest.getPassword())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "password必传!");
		}
		if (userLoginRequest.getRegisterChannel() != RegisterChannelEnum.BASE_ANDROID_APP
				&& userLoginRequest.getRegisterChannel() != RegisterChannelEnum.BASE_IOS_APP) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "registerChannel必传,且只能是0或者1 !");
		}
		Client findUser = new Client();
		findUser.setMobile(userLoginRequest.getMobile());
		Client findUserObj = clientService.findOne(findUser);
		if (findUserObj != null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户已经存在!");
		}
		AppSms appVerifCode = new AppSms();
		appVerifCode.setPhone(userLoginRequest.getMobile());
		appVerifCode.setOrderBy("APP_SMS.create_time desc");
		appVerifCode.setTemplate(AppSmsTemplateEnum.REGISTER);
		appVerifCode.setCode(userLoginRequest.getVerifCode());
		AppSms findAppVerifCode = appSmsService.findOne(appVerifCode);
		if (findAppVerifCode == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "无效的验证码");
		}
		if (DateTimeUtil.getMillisecondsOfTwoDate(Timestamp.from(findAppVerifCode.getActiveTime().toInstant()), DateTimeUtil.getSystemDate()) < 0) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "验证码已过期");
		}
		// 注册完成,此用户处于待审核阶段
		userLoginRequest.setCid(String.valueOf(new IdWorker().getId()));
		Client regiterClient = clientService.register(userLoginRequest);
		if (regiterClient == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "密码无效!");
		}
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(MagicConstants.SESSION_USER_ID, regiterClient.getId());
		claims.put(MagicConstants.SESSION_USER_MOBILE, regiterClient.getMobile());
		Token token = TokenGenerator.create(claims);
		return new ObjectDataResponse<Token>(token);
	}

	/**
	 * 处理第三方用户注册
	 */

	@IgnoreAuth
	@ResponseBody
	@ApiOperation(value = "处理第三方用户注册", notes = "处理第三方用户注册")
	@RequestMapping(value = "thirdPartyRegister", method = RequestMethod.POST)
	public ObjectDataResponse<Token> thirdPartyRegister(@RequestBody UserRegisterRequest userLoginRequest)
			throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginRequest.getMobile())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传!");
		}
		if (StringUtils.isEmpty(userLoginRequest.getCode())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "code必传!");
		}
		if (StringUtils.isEmpty(userLoginRequest.getHeadImage())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "headImage必传!");
		}
		AppSms appVerifCode = new AppSms();
		appVerifCode.setPhone(userLoginRequest.getMobile());
		appVerifCode.setOrderBy("APP_SMS.create_time desc");
		appVerifCode.setTemplate(AppSmsTemplateEnum.REGISTER);
		appVerifCode.setCode(userLoginRequest.getVerifCode());
		AppSms findAppVerifCode = appSmsService.findOne(appVerifCode);
		if (findAppVerifCode == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "无效的验证码");
		}
		if (DateTimeUtil.getMillisecondsOfTwoDate(Timestamp.from(findAppVerifCode.getActiveTime().toInstant()), DateTimeUtil.getSystemDate()) < 0) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "验证码已过期");
		}
		Client findUser = new Client();
		findUser.setMobile(userLoginRequest.getMobile());
		Client findUserObj = clientService.findOne(findUser);
		Client regiterClient = null;
		// 之前用户已经使用第三方平台注册过
		if (findUserObj != null && StringUtils.isNoneEmpty(findUserObj.getQqLoginCode())
				&& (userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_ANDROID_QQ
						|| userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_IOS_QQ)) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户已经存在!");
		} else if (findUserObj != null && StringUtils.isNoneEmpty(findUserObj.getWeixinLoginCode())
				&& (userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_ANDROIR_WECHAT
						|| userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_IOS_WECHAT)) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户已经存在!");
		} else if (findUserObj != null && StringUtils.isNoneEmpty(findUserObj.getWeiboLoginCode())
				&& (userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_ANDROID_WEOBO
						|| userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_IOS_WEOBO)) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户已经存在!");
		} else {
			if (findUserObj != null) {// 用户通过手机号注册过
				regiterClient = findUserObj;
			} else {// 用户从未注册过
				regiterClient = new Client();
				regiterClient.setRegisterChannel(userLoginRequest.getRegisterChannel());
				regiterClient.setCid(String.valueOf(new IdWorker().getId()));
			}
			regiterClient.setType(ClientTypeEnum.SELF);
			regiterClient.setPassword(PasswordHashUtil.createHash(userLoginRequest.getPassword()));
			regiterClient.setNickname(userLoginRequest.getNickname());
			regiterClient.setHeadImage(userLoginRequest.getHeadImage());
			regiterClient.setMobile(userLoginRequest.getMobile());
			regiterClient.setGender(userLoginRequest.getGender());
			if (userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_ANDROID_QQ
					|| userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_IOS_QQ) {
				regiterClient.setQqLoginCode(userLoginRequest.getCode());
			} else if (userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_ANDROIR_WECHAT
					|| userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_IOS_WECHAT) {
				regiterClient.setWeixinLoginCode(userLoginRequest.getCode());
			} else if (userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_ANDROID_WEOBO
					|| userLoginRequest.getRegisterChannel() == RegisterChannelEnum.APP_IOS_WEOBO) {
				regiterClient.setWeiboLoginCode(userLoginRequest.getCode());
			}
			if (findUserObj != null) {// 用户通过手机号注册过
				if (clientService.update(regiterClient) > 0) {
					Map<String, Object> claims = new HashMap<String, Object>();
					claims.put(MagicConstants.SESSION_USER_ID, regiterClient.getId());
					claims.put(MagicConstants.SESSION_USER_MOBILE, regiterClient.getMobile());
					Token token = TokenGenerator.create(claims);
					return new ObjectDataResponse<Token>(token);
				}
			} else {// 用户从未注册过
				if (clientService.insert(regiterClient) > 0) {

					ClientAccount clientAccount = new ClientAccount();
					clientAccount.setClientId(regiterClient.getId());
					clientAccountService.insert(clientAccount);

					if (!StringUtils.isEmpty(userLoginRequest.getShareCode())) {
						Client findClient = new Client();
						findClient.setShareCode(userLoginRequest.getShareCode());
						Client clientObj = clientService.findOne(findClient);
						if (clientObj != null) {
							ClientInvitation clientInvitation = new ClientInvitation();
							clientInvitation.setClientId(clientObj.getId());
							clientInvitation.setClientShareCode(regiterClient.getShareCode());
							clientInvitation.setPassiveClientId(regiterClient.getId());
							if (clientInvitationService.insert(clientInvitation) <= 0) {
								Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "邀请码错误");
							}
						}
						if (!clientAccountService.updateAccount(new ClientAccount() {

							private static final long serialVersionUID = 1L;

							{
								setClientId(clientObj.getId());
								setFollowNumber(1);
							}
						})) {
							Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "参数错误!");
						}
					}
					regiterClient.setShareCode(ShareCodeUtil.toSerialCode(regiterClient.getId()));
					clientService.update(regiterClient);

					Map<String, Object> claims = new HashMap<String, Object>();
					claims.put(MagicConstants.SESSION_USER_ID, regiterClient.getId());
					claims.put(MagicConstants.SESSION_USER_MOBILE, regiterClient.getMobile());
					Token token = TokenGenerator.create(claims);
					return new ObjectDataResponse<Token>(token);
				}
			}
		}
		return new ObjectDataResponse<Token>(null);
	}

	/**
	 * 刷新用户Token
	 */

	@ResponseBody
	@ApiOperation(value = "刷新用户Token", notes = "刷新用户Token")
	@RequestMapping(value = "referToken", method = RequestMethod.POST)
	public ObjectDataResponse<Token> referToken(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long userId,
			@RequestBody ReferTokenRequest referTokenRequest)
					throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		Client user = clientService.get(userId);
		if (user == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户不存在");
		}
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(MagicConstants.SESSION_USER_ID, user.getId());
		claims.put(MagicConstants.SESSION_USER_MOBILE, user.getMobile());
		Token token = TokenGenerator.create(claims);
		return new ObjectDataResponse<Token>(token);
	}

	/**
	 * 处理用户手机号登陆
	 */

	@IgnoreAuth
	@ResponseBody
	@ApiOperation(value = "手机号登陆", notes = "手机号登陆")
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public ObjectDataResponse<Token> login(HttpServletRequest request, HttpServletResponse response, @RequestBody UserLoginRequest userLoginRequest)
			throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginRequest.getMobile())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传!");
		}
		if (StringUtils.isEmpty(userLoginRequest.getPassword())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "password必传!");
		}
		Client findUser = new Client();
		findUser.setMobile(userLoginRequest.getMobile());
		Client user = clientService.findOne(findUser);
		if (user == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户不存在");
		}
		try {
			if (user.getStatus() == UserStatusEnum.DISABLE) {
				Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户处于冻结中,暂时无法操作");
			}
			if (!PasswordHashUtil.validatePassword(userLoginRequest.getPassword(), user.getPassword())) {
				Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "密码错误,请重新登录");
			}
		} catch (Exception e) {
			e.printStackTrace();
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "密码错误,请重新登录");
		}

		clientService.login(user);

		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(MagicConstants.SESSION_USER_ID, user.getId());
		claims.put(MagicConstants.SESSION_USER_MOBILE, user.getMobile());
		Token token = TokenGenerator.create(claims);
		// 留做测试使用
		new CookieManager(request, response).setCookie(MagicConstants.AUTH_TOKEN, token.getToken(), 7 * 24 * 60 * 60 * 100);
		return new ObjectDataResponse<Token>(token);
	}

	/**
	 * 验证客户端是否已经存在
	 */

	@IgnoreAuth
	@ResponseBody
	@ApiOperation(value = "验证客户端是否已经存在", notes = "验证客户端是否已经存在")
	@RequestMapping(value = "verifClient", method = RequestMethod.POST)
	public ObjectDataResponse<Boolean> verifClient(HttpServletRequest request, HttpServletResponse response, @RequestBody UserLoginRequest userLoginRequest) {
		if (StringUtils.isEmpty(userLoginRequest.getMobile())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "mobile必传!");
		}
		Client findUser = new Client();
		findUser.setMobile(userLoginRequest.getMobile());
		Client user = clientService.findOne(findUser);
		if (user == null) {
			return new ObjectDataResponse<Boolean>(true);
		}
		return new ObjectDataResponse<Boolean>(false);
	}

	/**
	 * 处理用户第三方登陆
	 */

	@IgnoreAuth
	@ResponseBody
	@ApiOperation(value = "用户第三方登陆", notes = "用户第三方登陆")
	@RequestMapping(value = "thirdPartyLogin", method = RequestMethod.POST)
	public ObjectDataResponse<Token> thirdPartyLogin(HttpServletRequest request, HttpServletResponse response, @RequestBody UserLoginRequest2 userLoginRequest)
			throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginRequest.getCode())) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "code必传!");
		}
		Client findUser = new Client();
		if (userLoginRequest.getLoginType() == UserLoginTypeEnum.QQ) {
			findUser.setQqLoginCode(userLoginRequest.getCode());
		} else if (userLoginRequest.getLoginType() == UserLoginTypeEnum.WEIXIN) {
			findUser.setWeixinLoginCode(userLoginRequest.getCode());
		} else if (userLoginRequest.getLoginType() == UserLoginTypeEnum.WEIBO) {
			findUser.setWeiboLoginCode(userLoginRequest.getCode());
		} else {
			Shift.fatal(StatusCode.UNAVAILABLE_EXCEPTION, "暂时不支持该类型操作");
		}
		Client user = clientService.findOne(findUser);
		if (user == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户不存在");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户处于冻结中,暂时无法操作");
		}
		clientService.login(user);
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(MagicConstants.SESSION_USER_ID, user.getId());
		claims.put(MagicConstants.SESSION_USER_MOBILE, user.getMobile());
		Token token = TokenGenerator.create(claims);
		// 留做测试使用
		new CookieManager(request, response).setCookie(MagicConstants.AUTH_TOKEN, token.getToken(), 7 * 24 * 60 * 60 * 100);
		return new ObjectDataResponse<Token>(token);
	}

	/**
	 * 获取首页达人信息
	 */

	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "获取首页达人信息", notes = "获取首页达人信息")
	@RequestMapping(value = "talentFind", method = RequestMethod.POST)
	public ObjectDataResponse<List<Client>> talentFind(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody Client client) {
		if (client.getPageSize() == null) {
			client.setPageSize(4);
		}
		return new ObjectDataResponse<List<Client>>(clientService.talentFind(client));
	}

	/**
	 * 获取首页精品视频
	 */

	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "获取首页精品视频", notes = "获取首页精品视频")
	@RequestMapping(value = "recommendVedio", method = RequestMethod.POST)
	public ObjectDataResponse<List<IssueAnswer>> recommendVedio(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody IssueAnswer issueAnswer) {
		issueAnswer.setOrderBy("I_ISSUE_ANSWER.thumbs_up_count desc");
		issueAnswer.setClientId(clientId);
		issueAnswer.setCityCode(null);
		List<IssueAnswer> issueAnswers = issueAnswerService.find(issueAnswer);
		return new ObjectDataResponse<List<IssueAnswer>>(issueAnswers);
	}

	/**
	 * 当前用户查看自己的信息
	 */

	@ResponseBody
	@ApiOperation(value = "当前用户查看自己的信息", notes = "当前用户查看自己的信息")
	@RequestMapping(value = "get", method = RequestMethod.POST)
	public ObjectDataResponse<Client> get(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId) {
		Client user = clientService.getRentClient(clientId, null);
		if (user == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户不存在");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户处于冻结中,暂时无法操作");
		}
		user.setPassword(null);
		user.setQqLoginCode(null);
		user.setWeixinLoginCode(null);
		user.setMobile(null);
		return new ObjectDataResponse<Client>(user);
	}

	/**
	 * 获取用户信息
	 */

	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "获取用户信息", notes = "获取用户信息")
	@RequestMapping(value = "lookClient", method = RequestMethod.POST)
	public ObjectDataResponse<Client> lookClient(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody Long lookClientId) {
		Client user = clientService.getRentClient(lookClientId, clientId);
		if (user == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户不存在");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "用户处于冻结中,暂时无法操作");
		}
		if (!StringUtils.isEmpty(user.getWechat())) {
			user.setHasBindWechat(true);
		}
		user.setBBean(null);
		user.setClientId(null);
		user.setMobile(null);
		user.setBBean(null);
		user.setAmount(null);
		user.setPassword(null);
		user.setQqLoginCode(null);
		user.setWeixinLoginCode(null);
		user.setMobile(null);
		user.setHasFollow(false);
		if (clientId != null && user.getFollowClientId() != null && clientId.longValue() == user.getFollowClientId().longValue()) {
			if (user.getFollowStatus() == ClientFollowStatusEnum.TWO_WAY_CONCERN || user.getFollowStatus() == ClientFollowStatusEnum.ACTIVE_CONCERN) {
				user.setHasFollow(true);
			}
		} else if (lookClientId != null && user.getFollowClientId() != null && lookClientId.longValue() == user.getFollowClientId().longValue()) {
			if (user.getFollowStatus() == ClientFollowStatusEnum.TWO_WAY_CONCERN || user.getFollowStatus() == ClientFollowStatusEnum.PASSIVE_CONCERN) {
				user.setHasFollow(true);
			}
		}
		if (clientId != null && clientId.longValue() != lookClientId.longValue()) {
			Client client = new Client();
			client.setId(lookClientId);
			client.setVisitorCount(1);
			clientService.updateCount(client);
			clientVisitorService.insertVisitor(clientId, lookClientId);
		}

		return new ObjectDataResponse<Client>(user);
	}

	/**
	 * 获取当前用户所发的视频
	 */

	@ResponseBody
	@ApiOperation(value = "获取当前用户所发的我答", notes = "获取用户所发的我答")
	@RequestMapping(value = "currentClientVedio", method = RequestMethod.POST)
	public ObjectDataResponse<List<IssueAnswer>> currentClientVedio(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody Issue issue) {
		issue.setAcceptorId(clientId);
		List<IssueAnswer> issueAnswers = issueAnswerService.findMyIssue(issue);
		for (IssueAnswer issueAnswer3 : issueAnswers) {
			if (issueAnswer3.getAmount() == null) {
				issueAnswer3.setAmount(new BigDecimal("12.9"));
			}
		}
		return new ObjectDataResponse<List<IssueAnswer>>(issueAnswers);
	}

	/**
	 * 获取当前用户信息
	 */

	@ResponseBody
	@ApiOperation(value = "获取当前用户提问", notes = "获取当前用户提问")
	@RequestMapping(value = "currentClientAnswer", method = RequestMethod.POST)
	public ObjectDataResponse<List<Issue>> currentClientAnswer(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody Issue issue) {
		issue.setClientId(clientId);
		issue.setHasPaySuccess(YesOrNoEnum.YES);
		List<Issue> issues = issueService.find2(issue);
		if (issues != null) {
			List<Long> ids = new ArrayList<Long>();
			for (Issue issue2 : issues) {
				ids.add(issue2.getId());
			}
			if (ids.size() > 0) {
				IssueAnswer findIssueAnswer = new IssueAnswer();
				findIssueAnswer.setIds(ids);
				List<IssueAnswer> issueAnswers = issueAnswerService.find(findIssueAnswer);
				if (issueAnswers != null && issueAnswers.size() > 0) {
					for (Issue issue2 : issues) {
						for (IssueAnswer issueAnswer : issueAnswers) {
							if (issueAnswer.getIssueId() == null) {
								continue;
							}
							if (issue2.getId().longValue() == issueAnswer.getIssueId().longValue()) {
								issue2.setIssueAnswer(issueAnswer);
							}
						}
					}
				}
			}
		}
		return new ObjectDataResponse<List<Issue>>(issues);
	}

	/**
	 * 获取用户所发的视频
	 */

	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "获取用户所发的视频", notes = "获取用户所发的视频")
	@RequestMapping(value = "clientVedio", method = RequestMethod.POST)
	public ObjectDataResponse<List<IssueAnswer>> clientAnswer(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody IssueAnswer issueAnswer) {
		issueAnswer.setHasMyVideo(true);
		List<IssueAnswer> issueAnswers = issueAnswerService.find(issueAnswer);
		return new ObjectDataResponse<List<IssueAnswer>>(issueAnswers);
	}

	/**
	 * 获取用户信息
	 */

	@ResponseBody
	@ApiOperation(value = "获取用户提问", notes = "获取当前用户提问")
	@RequestMapping(value = "clientAnswer", method = RequestMethod.POST)
	public ObjectDataResponse<List<Issue>> clientVedio(@RequestBody Issue issue) {
		List<Issue> issueAnswers = issueService.find(issue);
		return new ObjectDataResponse<List<Issue>>(issueAnswers);
	}

	/**
	 * 查看微信历史记录
	 */

	@ResponseBody
	@ApiOperation(value = "查看微信历史记录", notes = "查看微信历史记录")
	@RequestMapping(value = "clientWechat", method = RequestMethod.POST)
	public ObjectDataResponse<List<ClientWechat>> clientWechat(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody ClientWechat clientWechat) {
		clientWechat.setClientId(clientId);
		List<ClientWechat> clientWechats = clientWechatService.find(clientWechat);
		return new ObjectDataResponse<List<ClientWechat>>(clientWechats);
	}

	/**
	 * 查看我的邀请用户历史记录
	 */

	@ResponseBody
	@ApiOperation(value = "查看我的邀请用户历史记录", notes = "查看我的邀请用户历史记录")
	@RequestMapping(value = "clientInvitation", method = RequestMethod.POST)
	public ObjectDataResponse<List<ClientInvitation>> clientInvitation(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody ClientInvitation clientInvitation) {
		List<ClientInvitation> clientWechats = clientInvitationService.findClient(clientInvitation);
		return new ObjectDataResponse<List<ClientInvitation>>(clientWechats);
	}

	/**
	 * 客户申请退VIP押金
	 */

	@ResponseBody
	@ApiOperation(value = "客户申请退VIP押金", notes = "客户申请退VIP押金")
	@RequestMapping(value = "refundVip", method = RequestMethod.POST)
	public ObjectDataResponse<Boolean> refundVip(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody RefundRequest refundRequest) {
		if (refundRequest.getPayChannel() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "payChannel必传");
		}
		boolean success = orderRefundService.refundVip(clientId, refundRequest.getPayChannel());
		return new ObjectDataResponse<Boolean>(success);
	}

	/**
	 * 客户申请退可提现金额
	 */

	@ResponseBody
	@ApiOperation(value = "客户申请退可提现金额", notes = "客户申请退可提现金额")
	@RequestMapping(value = "refundDepositAmount", method = RequestMethod.POST)
	public ObjectDataResponse<Boolean> refundDepositAmount(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId,
			@RequestBody RefundRequest refundRequest) {
		if (refundRequest.getPayChannel() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "payChannel必传");
		}
		if (refundRequest.getAmount() == null) {
			Shift.fatal(StatusCode.INVALID_PARAMS_CONVERSION, "amount必传");
		}
		boolean success = orderRefundService.refundDepositAmount(clientId, refundRequest.getAmount(), refundRequest.getPayChannel());
		return new ObjectDataResponse<Boolean>(success);
	}

	/**
	 * 客户账户
	 */

	@ResponseBody
	@ApiOperation(value = "客户账户", notes = "客户账户")
	@RequestMapping(value = "getAccount", method = RequestMethod.POST)
	public ObjectDataResponse<ClientAccount> getAccount(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId) {
		ClientAccount account = new ClientAccount();
		account.setClientId(clientId);
		ClientAccount clientAccount = clientAccountService.findOne(account);
		Client client = clientService.get(clientId);
		clientAccount.setWechat(client.getWechat());
		return new ObjectDataResponse<ClientAccount>(clientAccount);
	}

	/**
	 * 客户访客
	 */
	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "客户访客", notes = "客户访客")
	@RequestMapping(value = "getVisitor", method = RequestMethod.POST)
	public ObjectDataResponse<List<ClientVisitor>> getVisitor(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long clientId,@RequestBody Long lookClientId) {
		ClientVisitor clientVisitor=new ClientVisitor();
		clientVisitor.setVisitorId(lookClientId);
		clientVisitor.setPageIndex(1);
		clientVisitor.setPageSize(8);
		List<ClientVisitor> clientVisitorList = clientVisitorService.findVisitor(clientVisitor);
		return new ObjectDataResponse<List<ClientVisitor>>(clientVisitorList);
	}
	

	/**
	 * 每日签到
	 */

	@ResponseBody
	@ApiOperation(value = "每日签到", notes = "每日签到")
	@RequestMapping(value = "getSign", method = RequestMethod.POST)
	public ObjectDataResponse<List<ClientSign>> getSign(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId) {
		ClientSign clientSign=new ClientSign();
		clientSign.setClientId(clientId);
		List<ClientSign> scuuess = clientSignService.find2(clientSign);
		return new ObjectDataResponse<List<ClientSign>>(scuuess);
	}

	/**
	 * 每日签到
	 */

	@ResponseBody
	@ApiOperation(value = "每日签到", notes = "每日签到")
	@RequestMapping(value = "signDay", method = RequestMethod.POST)
	public ObjectDataResponse<Integer> signDay(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId) {
		Integer scuuess = clientSignService.sign(clientId);
		return new ObjectDataResponse<Integer>(scuuess);
	}

	@ResponseBody
	@IgnoreAuth
	@ApiOperation(value = "每日总计签到", notes = "每日总计签到")
	@RequestMapping(value = "daySignCount", method = RequestMethod.POST)
	public ObjectDataResponse<Long> daySignCount(@ApiParam(name = "id", value = "用户id", hidden = true) @CurrentUserId Long clientId) {
		return new ObjectDataResponse<Long>(clientSignService.daySignCount());
	}
	
}
